<?php
/**
 * App核心类
 * 
 * Copyright (c) 2014~2019 https://desion.net All rights reserved.
 * Author: 阿林 QQ:120867629 <linhong00@gmail.com>
 */
declare (strict_types = 1);
namespace dsphp;
use dsphp\Container;
use InvalidArgumentException;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;

class App
{
    // 应用目录
    protected $appPath = '';
    // 框架目录
    protected $dsphpPath = '';


    /**
     * 架构方法
     */
    public function __construct()
    {
        $this->dsphpPath = DSPHP_PATH . 'dsphp' . DIRECTORY_SEPARATOR;
        $this->appPath   = DSPHP_PATH . DSPHP_WEB . DIRECTORY_SEPARATOR;
    }

    /**
     * 实例化逻辑
     *
     * @param string $name 逻辑名称
     * @return void
     */
    public function logic(string $name, array $argv = [], bool $new = false)
    {
        $name = $this->parseClass('logic', $name);
        return $this->make($name, $argv, $new);
    }

    /**
     * 助手
     * 
     * @param string $name 名称
     * @return void
     */
    public function helper(string $name)
    {
        if ($name == '') {
            return false;
        }

        $name = ucfirst($name);
        
        $namespace = 'dsphp\\helper\\'.$name . 'Helper';
        $handler   = $this->make($namespace);

        return $handler;
    }

    /**
     * 缓存
     * 
     * @param string $name 缓存名称
     * @return void
     */
    public function cache(string $name = '')
    {
        $config = $this->getConfig('cache');
        $cache  = $this->make('cache', [$config]);

        if ($name == '') {
            return $cache;
        }

        return $cache->init($name);
    }

    /**
     * 获取当前应用目录
     */
    public function getAppPath(): string
    {
        return $this->appPath;
    }

    /**
     * 获取当前应用类库目录
     */
    public function getClassPath(): string
    {
        return $this->appPath .'app'. DIRECTORY_SEPARATOR;
    }

    /**
     * 获取当前应用类库目录
     */
    public function getConfigPath(string $name): string
    {
        $name = $name ?: 'config';
        return $this->appPath .$name. DIRECTORY_SEPARATOR;
    }

    /**
     * 读取配置(只能一级)
     *
     * @param string $type 读取信息
     */
    public function getConfig(string $type):array
    {
        return $this->get('config')->get($type);
    }

    /**
     * 获取应用运行时目录
     */
    public function getRuntimePath(): string
    {
        return $this->appPath .'runtime' . DIRECTORY_SEPARATOR;
    }

    /**
     * 字符串命名风格转换
     * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
     *
     * @param string  $name    字符串
     * @param integer $type    转换类型
     * @param bool    $ucfirst 首字母是否大写（驼峰规则）
     */
    public static function parseName(string $name = null, int $type = 0, bool $ucfirst = true): string
    {
        if ($type) {
            $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                return strtoupper($match[1]);
            }, $name);
            return $ucfirst ? ucfirst($name) : lcfirst($name);
        }

        return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
    }

    /**
     * 解析应用类的类名
     *
     * @param string $layer  层名 controller model ...
     * @param string $name   类名
     * @param string $module 根
     */
    public function parseClass(string $layer, string $name, $module = 'app'): string
    {
        if ($layer != 'controller') {
            $name .= '_' . $layer;
        }

        $name  = str_replace(['/', '.'], '\\', $name);
        $array = explode('\\', $name);
        $class = self::parseName(array_pop($array), 1);
        $path  = $array ? implode('\\', $array) . '\\' : '';

        return $module.'\\' . $layer . '\\' . $path . $class;
    }

    /**
     * 获取容器中的对象实例
     *
     * @param string $abstract 类名或者标识
     * @return object
     */
    public function get($abstract)
    {
        if ($this->has($abstract)) {
            return $this->make($abstract);
        }

        throw new \Exception('class not exists: ' . $abstract);
    }

    /**
     * 绑定一个类实例到容器
     *
     * @param string $abstract 类名或者标识
     * @param object $instance 类的实例
     * @return $this
     */
    public function set(string $abstract, object $instance)
    {
        Container::instance($abstract, $instance);
        return $this;
    }

    /**
     * 判断容器中是否存在类及标识
     *
     * @param string $abstract 类名或者标识
     */
    protected function has($abstract)
    {
        return Container::has($abstract);
    }

    /**
     * 创建类的实例 已经存在则直接获取
     *
     * @param string $abstract    类名或者标识
     * @param array  $vars        变量
     * @param bool   $newInstance 是否每次创建新的实例
     * @return mixed
     */
    public function make(string $abstract, array $vars = [], bool $newInstance = false)
    {
        if (! $newInstance) {
            $object = Container::exists($abstract, true);
            if ($object) {
                return $object;
            }
        }
        
        $abstract = Container::getBindName($abstract);
        $object   = $this->invokeClass($abstract, $vars);
        
        // 更新
        if (! $newInstance) {
            $this->set($abstract, $object);
        }
        
        return $object;
    }

    /**
     * 调用反射执行类的方法 支持参数绑定
     * 
     * @param mixed $method 方法
     * @param array $vars   参数
     * @param bool  $accessible 设置是否可访问
     * @return mixed
     */
    public function invokeMethod($method, array $vars = [], bool $accessible = false)
    {
        try {
            if (is_array($method)) {
                $class   = is_object($method[0]) ? $method[0] : $this->invokeClass($method[0]);
                $reflect = new ReflectionMethod($class, $method[1]);
            } else {
                // 静态方法
                $reflect = new ReflectionMethod($method);
            }

            $args = $this->bindParams($reflect, $vars);

            if ($accessible) {
                $reflect->setAccessible($accessible);
            }
            
            return $reflect->invokeArgs($class ?? null, $args);
        } catch (ReflectionException $e) {
            if (is_array($method)) {
                $class    = is_object($method[0]) ? get_class($method[0]) : $method[0];
                $callback = $class . '::' . $method[1];
            } else {
                $callback = $method;
            }

            throw new \Exception('method not exists: ' . $callback . '()');
        }
    }

    /**
     * 调用反射执行类的实例化 支持依赖注入
     *
     * @param string $class 类名
     * @param array  $vars  参数
     * @return mixed
     */
    public function invokeClass(string $class, array $vars = [])
    {
        try {
            $reflect = new ReflectionClass($class);

            $constructor = $reflect->getConstructor();

            $args = $constructor ? $this->bindParams($constructor, $vars) : [];
            
            return $reflect->newInstanceArgs($args);
        } catch (ReflectionException $e) {
            throw new \Exception('class not exists: ' . $class);
        }
    }
    
    /**
     * 绑定参数
     *
     * @param \ReflectionMethod $reflect 反射类
     * @param array                                 $vars    参数
     * @return array
     */
    protected function bindParams($reflect, array $vars = []): array
    {
        if ($reflect->getNumberOfParameters() == 0) {
            return [];
        }

        // 判断数组类型 数字数组时按顺序绑定参数
        reset($vars);
        $type   = key($vars) === 0 ? 1 : 0;
        $params = $reflect->getParameters();
        $args   = [];

        foreach ($params as $param) {
            $name      = $param->getName();
            $lowerName = self::parseName($name);

            if (strpos($name, '_')) {
                list($name, $func) = explode('_', $name);
                $args[] = $this->$func($name);
                
                continue;
            }

            $class     = $param->getClass();

            if ($class) {
                $args[] = $this->getObjectParam($class->getName(), $vars);
            } elseif (1 == $type && !empty($vars)) {
                $args[] = array_shift($vars);
            } elseif (0 == $type && isset($vars[$name])) {
                $args[] = $vars[$name];
            } elseif (0 == $type && isset($vars[$lowerName])) {
                $args[] = $vars[$lowerName];
            } elseif ($param->isDefaultValueAvailable()) {
                $args[] = $param->getDefaultValue();
            } else {
                throw new InvalidArgumentException('method param miss:' . $name);
            }
        }

        return $args;
    }

    /**
     * 获取对象类型的参数值
     *
     * @param string $className 类名
     * @param array  $vars      参数
     * @return mixed
     */
    protected function getObjectParam(string $className, array &$vars)
    {
        $array = $vars;
        $value = array_shift($array);

        if ($value instanceof $className) {
            $result = $value;
            array_shift($vars);
        } else {
            $result = $this->make($className);
        }

        return $result;
    }
}
